import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { EdubaseSchoolTeachingUnitApi } from '#/api/edu/base/schoolTeachingUnit';
import type { DescriptionItemSchema } from '#/components/description';

import { h } from 'vue';

import {
  CommonStatusEnum,
  DICT_TYPE,
  EDU_SCHOOL_TEACHING_ORG_TYPE,
} from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { handleTree } from '@vben/utils';

import { Typography } from 'ant-design-vue';

import { z } from '#/adapter/form';
import { getSchoolPageSimple } from '#/api/edu/base/school';
import {
  checkOrg,
  getSchoolTeachingUnitSamplePage,
} from '#/api/edu/base/schoolTeachingUnit';
import { getDeptListCondition } from '#/api/system/dept';
import { getAdminUserPageSimplePermission } from '#/api/system/user';
import { DictTag } from '#/components/dict-tag';
import { getRangePickerDefaultProps } from '#/utils';

const { Paragraph } = Typography;
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showSchool',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'campusDictList',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showCampus',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showCollege',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showDepartment',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showFaculty',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showGroup',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'isSchool',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'distabledOrgType',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'name',
      label: '教学单位名称',
      component: 'Input',
      rules: 'required',
      componentProps: {
        placeholder: '请输入教学单位名称（如：计算机学院、小学部）',
      },
    },
    {
      fieldName: 'code',
      label: '教学单位编码',
      component: 'Input',
      rules: 'required',
      componentProps: {
        placeholder: '请输入教学单位编码',
      },
    },
    {
      fieldName: 'orgType',
      label: '教学单位类型',
      component: 'Select',
      rules: 'required',
      componentProps(values) {
        return {
          options: EDU_SCHOOL_TEACHING_ORG_TYPE,
          placeholder: '请选择教学单位类型',
          onChange: (val) => {
            if (val === '110103') {
              values.parentId = undefined;
            }
          },
        };
      },
      dependencies: {
        triggerFields: ['distabledOrgType'],
        show: (values) => !values.distabledOrgType,
      },
    },
    {
      fieldName: 'areaCode',
      label: '行政区划',
      component: 'ApiTreeSelect',
      dependencies: {
        triggerFields: ['isSchool'],
        show: (values) => !values.isSchool,
        componentProps(values) {
          return {
            async api() {
              const data = await getDeptListCondition({ type: 'area' });
              return handleTree(data);
            },
            key: values.isSchool || 0,
            labelField: 'name',
            valueField: 'id',
            childrenField: 'children',
            placeholder: '请选择行政区划',
            treeDefaultExpandAll: true,
            allowClear: true,
          };
        },
      },
    },
    {
      fieldName: 'schoolId',
      label: '所属学校',
      component: 'ApiPagingSelect',
      dependencies: {
        triggerFields: ['showSchool', 'areaCode'],
        show: (values) => values.showSchool,
        componentProps(values) {
          return {
            allowClear: true,
            key: values.areaCode + values.showSchool || 0,
            async api() {
              return await getSchoolPageSimple(
                {
                  status: 1,
                  schoolCampusType: 0,
                  areaCode: values.areaCode,
                  pageNo: 1,
                  pageSize: 100,
                },
                false,
                false,
              );
            },
            labelField: 'schoolName',
            valueField: 'id',
            placeholder: '请选择学校',
            onChange: async (val, option: any) => {
              if (val) {
                const res = await checkOrg(val);
                values.showCampus = res.showCampus;
                values.showCollege = res.showCollege;
                values.showDepartment = res.showDepartment;
                values.showFaculty = res.showFaculty;
                values.showGroup = res.showGroup;
                values.campusDictList = res.showCampus
                  ? res.children || []
                  : [];
              } else {
                values.showCampus = false;
                values.showCollege = false;
                values.showDepartment = false;
                values.showFaculty = false;
                values.showGroup = false;
                values.campusDictList = [];
                values.campusId = undefined;
              }
            },
          };
        },
      },
    },
    {
      fieldName: 'campusId',
      label: '所属校区',
      component: 'Select',
      dependencies: {
        triggerFields: ['showCampus', 'campusDictList'],
        show: (values) => values.showCampus,
        componentProps(values) {
          return {
            allowClear: true,
            key: values.showCampus || false,
            fieldNames: {
              label: 'name',
              value: 'id',
            },
            options: values.campusDictList || [],
            placeholder: '请选择校区',
          };
        },
      },
    },
    {
      fieldName: 'parentId',
      label: '父级单位',
      component: 'ApiPagingSelect',
      dependencies: {
        triggerFields: ['orgType', 'areaCode', 'schoolId', 'campusId'],
        show: (values) => values.orgType !== '110103',
        componentProps(values) {
          return {
            allowClear: true,
            key: values.areaCode || 0,
            async api() {
              return await getSchoolTeachingUnitSamplePage(
                {
                  status: 1,
                  areaCode: values.areaCode,
                  schoolId: values.schoolId,
                  campusId: values.campusId,
                  pageNo: 1,
                  pageSize: 100,
                },
                false,
                false,
              );
            },
            labelField: 'name',
            valueField: 'id',
            placeholder: '请选择上级教学单位',
          };
        },
      },
    },
    {
      fieldName: 'leaderId',
      label: '负责人',
      component: 'ApiPagingSelect',
      componentProps(values) {
        return {
          api: getAdminUserPageSimplePermission,
          labelField: 'text',
          valueField: 'id',
          placeholder: '请选择联系人对应的用户',
          onChange: (val, option: any) => {
            if (val) {
              values.leaderName = option.fullName || option.nickname;
              values.leaderCellphone = option.mobile;
              values.leaderIdcard = option.idcard;
            }
          },
        };
      },
    },
    {
      fieldName: 'leaderName',
      label: '负责人姓名',
      component: 'Input',
      componentProps: {
        placeholder: '请输入负责人姓名',
      },
    },
    {
      fieldName: 'leaderIdcard',
      label: '负责人身份证',
      component: 'Input',
      componentProps: {
        placeholder: '请输入负责人身份证',
      },
    },
    {
      fieldName: 'leaderCellphone',
      label: '负责人手机',
      rules: 'mobile',
      component: 'Input',
      componentProps: {
        placeholder: '请输入负责人手机',
      },
    },
    {
      fieldName: 'leaderTelphone',
      label: '负责人固定电话',
      component: 'Input',
      componentProps: {
        placeholder: '请输入负责人固定电话',
      },
    },
    {
      fieldName: 'status',
      label: '状态',
      rules: z.number().default(CommonStatusEnum.ENABLE),
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
        placeholder: '请选择有效状态',
      },
    },
    {
      fieldName: 'sort',
      label: '排序号',
      component: 'InputNumber',
      componentProps: {
        min: 0,
        placeholder: '请输入排序号',
      },
    },
    {
      fieldName: 'remarks',
      label: '描述',
      component: 'Textarea',
      componentProps: {
        rows: 4,
        placeholder: '请输入描述',
      },
    },
    {
      fieldName: 'briefIntroduction',
      label: '简介',
      component: 'RichTextarea',
      componentProps: {
        placeholder: '请输入简介',
      },
    },
  ];
}

/** 详情页字段 */
export function useDetailSchema(): DescriptionItemSchema[] {
  return [
    {
      label: '教学单位名称',
      field: 'name',
    },
    {
      label: '教学单位编码',
      field: 'code',
    },
    {
      label: '教学单位类型',
      field: 'orgType',
      render: (val) => {
        return h(DictTag, {
          options: EDU_SCHOOL_TEACHING_ORG_TYPE,
          value: val,
        });
      },
    },
    {
      label: '负责人姓名',
      field: 'leaderName',
    },
    {
      label: '负责人身份证',
      field: 'leaderIdcard',
    },
    {
      label: '负责人手机',
      field: 'leaderCellphone',
    },
    {
      label: '负责人固定电话',
      field: 'leaderTelphone',
    },
    {
      label: '状态',
      field: 'status',
      render: (val) => {
        return h(DictTag, {
          type: DICT_TYPE.COMMON_STATUS,
          value: val,
        });
      },
    },
    {
      label: '排序号',
      field: 'sort',
    },
    {
      label: '描述',
      field: 'remarks',
      render: (val) =>
        h('div', {
          innerHTML: val,
          class: 'whitespace-pre-wrap text-sm leading-relaxed',
        }),
    },
    {
      label: '简介（富文本）',
      field: 'briefIntroduction',
      render: (val) =>
        h('div', {
          innerHTML: val,
        }),
    },
    {
      label: '行政区划',
      field: 'areaName',
    },
    {
      label: '所属学校',
      field: 'schoolName',
    },
    {
      label: '所属校区',
      field: 'campusName',
    },
    {
      label: '父级单位',
      field: 'parentName',
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'showSchool',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showCampus',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'campusDictList',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showCollege',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showDepartment',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showFaculty',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'showGroup',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'isSchool',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'distabledOrgType',
      component: 'RadioGroup',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'name',
      label: '教学单位名称',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入教学单位名称（如：计算机学院、高一年级组）',
      },
    },
    {
      fieldName: 'code',
      label: '教学单位编码',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入教学单位编码',
      },
    },
    {
      fieldName: 'orgType',
      label: '教学单位类型',
      component: 'Select',
      componentProps(values) {
        return {
          allowClear: true,
          options: EDU_SCHOOL_TEACHING_ORG_TYPE,
          placeholder: '请选择教学单位类型',
          onChange: (val) => {
            if (val === '110103') {
              values.parentId = undefined;
            }
          },
        };
      },
      dependencies: {
        triggerFields: ['distabledOrgType'],
        show: (values) => !values.distabledOrgType,
      },
    },
    {
      fieldName: 'leaderName',
      label: '负责人姓名',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入负责人姓名',
      },
    },
    {
      fieldName: 'leaderIdcard',
      label: '负责人身份证',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入负责人身份证',
      },
    },
    {
      fieldName: 'leaderCellphone',
      label: '负责人手机',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入负责人手机',
      },
    },
    {
      fieldName: 'leaderTelphone',
      label: '负责人固定电话',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入负责人固定电话',
      },
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.COMMON_STATUS),
        placeholder: '请选择状态',
      },
    },
    {
      fieldName: 'areaCode',
      label: '行政区划',
      component: 'ApiTreeSelect',
      componentProps: {
        api: async () => {
          const data = await getDeptListCondition({ type: 'area' });
          return handleTree(data);
        },
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        placeholder: '请选择行政区划',
        treeDefaultExpandAll: true,
        allowClear: true,
      },
      dependencies: {
        triggerFields: ['isSchool'],
        show: (values) => !values.isSchool,
      },
    },
    {
      fieldName: 'schoolId',
      label: '所属学校',
      component: 'ApiPagingSelect',
      dependencies: {
        triggerFields: ['showSchool', 'areaCode'],
        show: (values) =>
          values.showSchool || (values.areaCode && !values.showSchool),
        componentProps(values) {
          return {
            allowClear: true,
            key: values.areaCode + values.showSchool || 0,
            async api() {
              return await getSchoolPageSimple(
                {
                  status: 1,
                  schoolCampusType: 0,
                  areaCode: values.areaCode,
                  pageNo: 1,
                  pageSize: 100,
                },
                false,
                false,
              );
            },
            labelField: 'schoolName',
            valueField: 'id',
            placeholder: '请选择学校',
            onChange: async (val, option: any) => {
              if (val) {
                const res = await checkOrg(val);
                values.showCampus = res.showCampus;
                values.showCollege = res.showCollege;
                values.showDepartment = res.showDepartment;
                values.showFaculty = res.showFaculty;
                values.showGroup = res.showGroup;
                values.campusDictList = res.showCampus
                  ? res.children || []
                  : [];
              } else {
                values.showCampus = false;
                values.showCollege = false;
                values.showDepartment = false;
                values.showFaculty = false;
                values.showGroup = false;
                values.campusDictList = [];
                values.campusId = undefined;
              }
            },
          };
        },
      },
    },
    {
      fieldName: 'campusId',
      label: '所属校区',
      component: 'Select',
      dependencies: {
        triggerFields: ['showCampus', 'campusDictList'],
        show: (values) => values.showCampus,
        componentProps(values) {
          return {
            allowClear: true,
            fieldNames: {
              label: 'name',
              value: 'id',
            },
            options: values.campusDictList || [],
            placeholder: '请选择校区',
          };
        },
      },
    },
    {
      fieldName: 'parentId',
      label: '父级单位',
      component: 'ApiPagingSelect',
      dependencies: {
        triggerFields: ['orgType', 'areaCode', 'schoolId', 'campusId'],
        show: (values) => values.orgType !== '110103',
        componentProps(values) {
          return {
            allowClear: true,
            key: values.areaCode || 0,
            async api() {
              return await getSchoolTeachingUnitSamplePage(
                {
                  status: 1,
                  areaCode: values.areaCode,
                  schoolId: values.schoolId,
                  campusId: values.campusId,
                  pageNo: 1,
                  pageSize: 100,
                },
                false,
                false,
              );
            },
            labelField: 'name',
            valueField: 'id',
            placeholder: '请选择上级教学单位',
          };
        },
      },
    },
    {
      fieldName: 'createTime',
      label: '创建时间',
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions<EdubaseSchoolTeachingUnitApi.SchoolTeachingUnit>['columns'] {
  return [
    { type: 'checkbox', width: 40 },
    {
      field: 'id',
      title: '主键',
      minWidth: 120,
      visible: false,
    },

    {
      field: 'name',
      title: '教学单位名称',
      minWidth: 120,
    },
    {
      field: 'code',
      title: '教学单位编码',
      minWidth: 120,
    },
    {
      field: 'orgType',
      title: '教学单位类型',
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { options: EDU_SCHOOL_TEACHING_ORG_TYPE },
      },
    },
    {
      field: 'leaderId',
      title: '负责人id',
      minWidth: 120,
      visible: false,
    },
    {
      field: 'leaderName',
      title: '负责人姓名',
      minWidth: 120,
    },
    {
      field: 'leaderIdcard',
      title: '负责人身份证',
      minWidth: 120,
    },
    {
      field: 'leaderCellphone',
      title: '负责人手机',
      minWidth: 120,
    },
    {
      field: 'leaderTelphone',
      title: '负责人固定电话',
      minWidth: 120,
    },
    {
      field: 'status',
      title: '状态',
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.COMMON_STATUS },
      },
    },
    {
      field: 'sort',
      title: '排序号',
      minWidth: 120,
    },
    {
      field: 'remarks',
      title: '描述',
      minWidth: 120,
    },
    {
      field: 'parentName',
      title: '父级单位',
      minWidth: 200,
    },
    {
      field: 'areaName',
      title: '行政区划名称',
      minWidth: 120,
    },
    {
      field: 'schoolName',
      title: '所属学校',
      minWidth: 200,
    },
    {
      field: 'campusName',
      title: '所属校区',
      minWidth: 200,
    },
    {
      field: 'createTime',
      title: '创建时间',
      minWidth: 160,
      formatter: 'formatDateTime',
    },
    {
      field: 'actions',
      title: '操作',
      width: 200,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}
